<template>
	<view class="scanCode" @click="scanCode">
		<text>扫一扫</text>
		<image src="/static/profile/scan_qrCode.png"></image>
	</view>
</template>

<script>
	const app = getApp()

	export default {
		name: "scanCode",
		data() {
			return {

			};
		},
		methods: {
			// 扫码
			scanCode() {
				uni.scanCode({
					onlyFromCamera: true
				}).then(res => {
					console.log(JSON.parse(res[1].result));
					const scan_time = new Date().getTime()
					// 将json数据转换为object
					const qrCode_value = JSON.parse(res[1].result)

					uni.showModal({
						title: '提示',
						content: '是否取回此物品'
					}).then(res => {
						console.log(res);
						// 如果点击确定获取此物品
						if (res[1].confirm) {
							uni.showLoading({
								title: '加载中...'
							})
							// 如果二维码超过一分钟则失效
							if(scan_time - qrCode_value.create_time > 60000){
								uni.hideLoading()
								return uni.showToast({
									title:'二维码失效',
									icon:'error'
								})
							}
							// 如果二维码为自己生成的二维码
							if(app.globalData.userInfo.profile.student_ID == qrCode_value.UID){
								uni.hideLoading()
								return uni.showToast({
									title:'请扫他人的二维码',
									icon:'error'
								})
							}
							// 获取_id的数据，判断是否已被找回
							this.get_scan_info(qrCode_value._id).then(res => {
								console.log(res);
								// 如果已被找回并重复扫码就提示已被找回
								if (res.result.data.is_found) {
									uni.hideLoading()
									return uni.showToast({
										title: '物品已被找回',
										icon: "error"
									})
								} else {
									// 如果没有被找回则存入数据库
									this.update_scan_info(qrCode_value)
								}
							})
						}
					})

				})
			},

			// 获取扫码的数据
			get_scan_info(_id) {
				return new Promise(resolve => {
					wx.cloud.callFunction({
						name: 'get_scan_info',
						data: {
							_id
						}
					}).then(res => {
						resolve(res)
					})
				})
			},

			// 扫码后将数据改为被找回，
			// 并且将_id分别放入扫码者和出示二维码者的数据库中
			update_scan_info({
				UID,
				_id
			}) {
				// 获取自己的学号
				const own_UID = app.globalData.userInfo.profile.student_ID
				wx.cloud.callFunction({
					name: 'update_scan_info',
					data: {
						own_UID,
						UID,
						_id
					}
				}).then(res => {
					console.log('123456789', res);
					uni.showToast({
						title: '取回成功',
						icon: "success"
					})
				})
			},

		}
	}
</script>

<style scoped lang="scss">
	.scanCode {
		margin-top: 5rpx;
		padding: 10rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;

		text {
			font-size: 32rpx;
			color: #B3B3B3;
		}

		image {
			width: 36rpx;
			height: 36rpx;
		}
	}
</style>
